package view.Prize
{
	import flash.display.Bitmap;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import starling.animation.Transitions;
	import starling.animation.Tween;
	import starling.core.Starling;
	import starling.display.Image;
	import starling.display.MovieClip;
	import starling.display.Quad;
	import starling.display.Sprite;
	import starling.textures.Texture;
	import starling.utils.deg2rad;
	
	import track.TrackFactory;
	
	import utils.LevelConfigXmlUtils;
	import utils.ShakeObjUtils;
	import utils.SoundManager;
	import utils.Vector2D;
	
	import view.Score.ScoreManager;
	import view.SkillBar.BulletBoxView;
	import view.SkillBar.SkillBarManager;
	
	public class PrizeView extends Sprite
	{
        /**飞行物的ID号*/
		private var _prizeNo:uint;
        /**飞行物的翅膀*/
		private var wingMc:MovieClip;
        /**飞行物的图像*/
		private var _prizeImg:Image;
        /**飞行物代表的名字*/
		private var _prizeName:String;
        /**飞行物代表的速度*/
		private var _speed:Number;
		private var _energon:String;
		private var _price:uint;
		private var _trackType:uint;
		private var _energonContainer:Sprite;         //存放能量块的容器
		private var _energonVec:Vector.<EnergonView>;
		private var _energonColorIdVec:Vector.<uint>;
		/**用来碰撞检测的矩形方块*/
		private var _hitRect:Quad;
		private var _position:Vector2D;  //位置
		private var _velocity:Vector2D;  //速度大小、方向
		private var prizeList:XMLList;
		/**
		 * _type: 飞行物所属类别
		 * "prize": 飞行物为奖品
		 * "bullet": 飞行物为子弹  关卡配置文件中，若飞行物为子弹，名字后面需要附带1
		 * */
		private var _type:String;
		private static const FACTOR:Number = 0.2;
		
		public static const WRAP:String = "wrap";
		public static const BOUNCE:String = "bounce";
		private var _edgeBehavior:String = WRAP;
		private var _mass:uint = 1;
		private var _maxSpeed:Number;
		private var _maxForce:Number = 0.6;
		private var _steeringForce:Vector2D;
		private var _arrivalThreshold:Number = 5;
		private var _pathIndex:uint;
		private var _pathThreshold:uint = 40;
		private var _pathArr:Array;
		public function PrizeView(prizeNo:uint):void
		{
			super();
			_prizeNo = prizeNo;
			_energonVec = new Vector.<EnergonView>();
			_energonColorIdVec = new Vector.<uint>;
			_position = new Vector2D();
			_velocity = new Vector2D();
			_steeringForce = new Vector2D();
			_pathArr = new Array();
			//add wings
			var wingFrames:Vector.<Texture> = Assets.getWingAtlas().getTextures("WingBasic");
			wingMc = new MovieClip(wingFrames, 45);
			Starling.juggler.add(wingMc);
			addChild(wingMc);
			
			/**通过初始化的prizeNo在关卡配置中查找对应的飞行物的名字和速度  */
			prizeList = LevelConfigXmlUtils.getInstance().xml.child("prizeConfig").child("prize");
			var i:uint;
			var len:uint = prizeList.length();
			for(i=0;i<len;i++){
				if(prizeList[i].@no == _prizeNo){
					prizeName = prizeList[i].@name;   
					_speed = prizeList[i].@speed * FACTOR;
					_maxSpeed = _speed + 2 * FACTOR;
					_energon = prizeList[i].@energon;
					_price = prizeList[i].@price;
					_trackType = prizeList[i].@trackType;
					break;
				}
			}
			
			var subTypeId:uint;
			switch(_trackType){
				case Const.TRACK_LINE:      //0 直线型
					subTypeId = Math.floor(Math.random() * 12);
					_pathArr = TrackFactory.makePath(0, subTypeId);
					break;
				case Const.TRACK_C2C:		//1对角线型
					subTypeId = Math.floor(Math.random() * 4);
					_pathArr = TrackFactory.makePath(1, subTypeId);
					break;
				case Const.TRACK_REC:		//2矩形	
					subTypeId = Math.floor(Math.random() * 4);
					_pathArr = TrackFactory.makePath(2, subTypeId);
					break;
				case Const.TRACK_CIRCLE:	//3圆形
					subTypeId = Math.floor(Math.random() * 4);
					_pathArr = TrackFactory.makePath(3, subTypeId);
					_maxForce = 0.4;
					break;
				case Const.TRACK_8:			//4 8字型
					subTypeId = Math.floor(Math.random() * 4);
					_pathArr = TrackFactory.makePath(4, subTypeId);
					break;
			}
			
            /**根据名字后缀检测飞行物的类型
             * 后缀带1为特殊子弹
             * 没带1为普通飞行物
             */
			if(prizeName.charAt(prizeName.length - 1) == "1"){
				_type = "bullet";
			}else{
				_type = "prize";
			}
			
			//add prizeImg
			_prizeImg = new Image(Assets.getAtlas().getTexture(prizeName));
			addChild(_prizeImg);
			_prizeImg.x = 60;
			_prizeImg.y = -10;
			
			drawEnergonContainer();
			drawHitRect();
			this.pivotX = 100;
			this.pivotY = 100;
			this.touchable = false;
		}
		
		private var twinkleTimer:Timer;
		public function twinkle():void{
			twinkleTimer = new Timer(4000);
			twinkleTimer.addEventListener(TimerEvent.TIMER, twinkleStart);
			twinkleTimer.start();
		}
		
		private function twinkleStart(event:TimerEvent):void
		{
			this.x = Math.random() * Const.RECT_REGION.width + Const.RECT_REGION.left;
			this.y = Math.random() * Const.RECT_REGION.height + Const.RECT_REGION.top;
		}
		
		private function drawEnergonContainer():void
		{
			_energonContainer = new Sprite();
			_energonContainer.x = 100;
			_energonContainer.y = 100;
			addChild(_energonContainer);
			
			/**
			 * 11,22-----> split(",")------>arr = [11,22]
			 * */
			var arr:Array = _energon.split(",");
			var energonRowsNum:uint = arr.length;
			for(var i:uint = 0 ; i < energonRowsNum; i++){
				var id:uint = uint(arr[i].substr(0, 1));
				var energonNum:uint = arr[i].length;
				addEnergons(i, id, energonNum);
				for(var j:uint = 0; j < energonNum; j++){
					_energonColorIdVec.push(id);
				}
			}
		}
		
		//当泡泡打中道具的时候，对能量块进行处理
		public function processEnergon(colorId:uint):void{
			if(hasThisColor(colorId) && _energonVec){
				moveOut(colorId);
			}else{
				return;   //当所有能量块都被打完，则不必处理
			}
		}
		
		//当满足打中条件的时候，移除能量块
		/**是否还有能量块*/
		public function moveOut(colorId:int):void{
			var id:String = colorId.toString();
			var index:int = _energonColorIdVec.lastIndexOf(id);
			if(index == -1)         //没有找到
				return;
			_energonColorIdVec.splice(index,1);
			var e:EnergonView = _energonVec[index];
			_energonVec.splice(index,1);
			e.fadeOut();
			//shake
			if(_energonColorIdVec.length > 0 &&_energonColorIdVec.lastIndexOf(id) == -1){
				SoundManager.getInstance().playSound("hurt", false);
				shake();
			}else{
				SoundManager.getInstance().playSound("dispear", false);
			}
			e = null;
			if(_energonVec.length == 0){
				if(_type == "prize")
			        fadeOutAndDestroy();
				else if (_type == "bullet")
					moveToBubBar();
			}
		}

        /**淡出销毁处理*/
        private function fadeOutAndDestroy():void{
			var scoreAdd:uint = this._price * 10;       //分数按照价格的10倍处理
			ScoreManager.getInstance().score += scoreAdd;
			ScoreManager.getInstance().showFloatScore(this.x, this.y, scoreAdd);
				
			var tween:Tween = new Tween(this, 1.0, Transitions.EASE_OUT);
			tween.fadeTo(0);   
			Starling.juggler.add(tween);
			tween.onComplete = destroy;
        }

        private function destroy():void{
            this.removeFromParent(true);
			if(twinkleTimer && twinkleTimer.hasEventListener(TimerEvent.TIMER)){
				twinkleTimer.removeEventListener(TimerEvent.TIMER, twinkleStart);
			}
			if(twinkleTimer && twinkleTimer.running)	twinkleTimer.stop();
			twinkleTimer = null;
            this.dispose();
        }

        public function shake():void{
			ShakeObjUtils.getInstance().shakeObj(this, 1, 30, deg2rad(20));
        }
		/**
		 * 当飞行物为特殊子弹被打下来的时候，进入技能栏
		 */
		private function moveToBubBar():void{
			var endX:int;
			var endY:int;
			var vec:Vector.<BulletBoxView> = SkillBarManager.getInstance().skillBar.boxVec;
			for(var i:uint = 0; i < 3; i++){
				if(vec[i].prizeNo == this.prizeNo){
					switch(i){
						case 0:
							endX = Const.SKILL_BAR_BUBBLE1_X;
							endY = Const.SKILL_BAR_BUBBLE1_Y;
							break;       
						case 1:
							endX = Const.SKILL_BAR_BUBBLE2_X;
							endY = Const.SKILL_BAR_BUBBLE2_Y;
							break;
						case 2:
							endX = Const.SKILL_BAR_BUBBLE3_X;
							endY = Const.SKILL_BAR_BUBBLE3_Y;
							break;
					}
					break;
				}
				if(vec[i].isEmpty){
					switch(i){
						case 0:
							endX = Const.SKILL_BAR_BUBBLE1_X;
							endY = Const.SKILL_BAR_BUBBLE1_Y;
							break;       
						case 1:
							endX = Const.SKILL_BAR_BUBBLE2_X;
							endY = Const.SKILL_BAR_BUBBLE2_Y;
							break;
						case 2:
							endX = Const.SKILL_BAR_BUBBLE3_X;
							endY = Const.SKILL_BAR_BUBBLE3_Y;
							break;
					}
					break;
				}
			}
			var tween:Tween = new Tween(this, 1.0, Transitions.EASE_OUT);
			tween.animate("x", endX);
			tween.animate("y", endY);
			tween.scaleTo(0.5);
			tween.fadeTo(0);   
			Starling.juggler.add(tween);
            //运动到技能栏
			tween.onComplete = onFinishTweenBar;
		}
		
		private function onFinishTweenBar():void{
			SkillBarManager.getInstance().addBullet(this);
		}
		
		private function hasThisColor(colorId:uint):Boolean{
			if(this.energon.indexOf(colorId.toString()) != -1)
				return true;
			return false;
		}

		private function addEnergons(row:uint, id:uint, energonNum:uint):void
		{
			var hSpace:uint = 2;          //水平间隙
			var vSpace:uint = 1;           //竖直间隙
			for(var i:uint = 0; i < energonNum; i++){
				var e:EnergonView = new EnergonView(id);
				e.x = (e.width + hSpace) * i;
				e.y = (e.height + vSpace) * row;
				_energonContainer.addChild(e);
				_energonVec.push(e);
			}
		}
		
		private function drawHitRect():void{
			_hitRect = new Quad(50, 50, 0x000000, true);
			_hitRect.alpha = 0;
			_hitRect.x = _prizeImg.x + (_prizeImg.width - _hitRect.width) * 0.5;
			_hitRect.y = _prizeImg.y + (_prizeImg.height - _hitRect.height) * 0.5;
			addChild(_hitRect);
		}
		
		public function update():void{
			_steeringForce.truncate(_maxForce);
			_steeringForce = _steeringForce.divide(_mass);
			_velocity = _velocity.add(_steeringForce);
			_steeringForce = new Vector2D();
			
			_velocity.truncate(_maxSpeed);
			_position = _position.add(_velocity);
			x = _position.x;
			y = _position.y;
		}
		
		public function seek(target:Vector2D):void{
			var desiredVelocity:Vector2D = target.subtract(_position);
			desiredVelocity.normalize();
			desiredVelocity = desiredVelocity.multiply(_maxSpeed);
			var force:Vector2D = desiredVelocity.subtract(_velocity);
			_steeringForce = _steeringForce.add(force);
		}

		public function followPath(path:Array, loop:Boolean = true):void{
			var wayPoint:Vector2D = path[_pathIndex];
			if(wayPoint == null)	return;
			if(_position.dist(wayPoint) < _pathThreshold){
				if(_pathIndex >= path.length - 1){
					if(loop){
						_pathIndex = 0;
					}
				}else{
					_pathIndex ++;
				}
			}
			seek(wayPoint);
		}

/*-----------------------------------getter and setter-----------------------------------*/
		public function get energon():String
		{
			return _energon;
		}

		public function set energon(value:String):void
		{
			_energon = value;
		}

		public function get energonVec():Vector.<EnergonView>
		{
			return _energonVec;
		}

		public function set energonVec(value:Vector.<EnergonView>):void
		{
			_energonVec = value;
		}

		public function get position():Vector2D
		{
			return _position;
		}

		public function set position(value:Vector2D):void
		{
			_position = value;
		}

		public function get velocity():Vector2D
		{
			return _velocity;
		}

		public function set velocity(value:Vector2D):void
		{
			_velocity = value;
		}

		public function get speed():Number
		{
			return _speed;
		}

		public function set speed(value:Number):void
		{
			_speed = value;
		}

		/**用来碰撞检测的矩形方块*/
		public function get hitRect():Quad
		{
			return _hitRect;
		}

		public function set hitRect(value:Quad):void
		{
			_hitRect = value;
		}

		public function get prizeImg():Image
		{
			return new Image(Assets.getAtlas().getTexture(_prizeName));
		}

        public function clonePrizeImg():Image{
			return new Image(Assets.getAtlas().getTexture(_prizeName));
		}
        
		public function set prizeImg(value:Image):void
		{
			_prizeImg = value;
		}

		public function get prizeNo():uint
		{
			return _prizeNo;
		}

		public function get prizeName():String
		{
			return _prizeName;
		}

		public function set prizeName(value:String):void
		{
			_prizeName = value;
		}

		public function get edgeBehavior():String
		{
			return _edgeBehavior;
		}

		public function set edgeBehavior(value:String):void
		{
			_edgeBehavior = value;
		}

		public function get maxSpeed():Number
		{
			return _maxSpeed;
		}

		public function set maxSpeed(value:Number):void
		{
			_maxSpeed = value;
		}

		public function get maxForce():Number
		{
			return _maxForce;
		}

		public function set maxForce(value:Number):void
		{
			_maxForce = value;
		}

		public function get arrivalThreshold():Number
		{
			return _arrivalThreshold;
		}

		public function set arrivalThreshold(value:Number):void
		{
			_arrivalThreshold = value;
		}

		public function get trackType():uint
		{
			return _trackType;
		}

		public function set trackType(value:uint):void
		{
			_trackType = value;
		}

		public function get pathArr():Array
		{
			return _pathArr;
		}

		public function set pathArr(value:Array):void
		{
			_pathArr = value;
		}

		
	}
}
